<template>
  <div class="attr-item">
    <div class="attr-item-ul" ref="sortList">
      <div
        class="attr-item-ul-li"
        v-for="(item, index) in curActionColumn"
        :key="item.id"
      >
        <a class="li-title" @click="methods.onChangeEditItem(item, index)">
          <Icon icon="ant-design:holder-outlined" />
          {{ item.title }}
        </a>
        <div class="li-icon" @click="methods.onChangeEditItem(item, index)">
          <Icon icon="ant-design:form-outlined" />
        </div>
        <div class="li-icon" @click="methods.onDeleteItem(index)">
          <Icon icon="ant-design:delete-outlined" />
        </div>
      </div>
      <Button class="attr-item-add" @click="methods.onAddItem">
        添加一项
      </Button>
    </div>

    <Modal v-model:open="isEdit" title="修改标签项" @ok="methods.onConfirm">
      <div class="item-edit">
        <BwConfigInput v-model:value="curEditItem.title" title="标题" />
        <BwConfigSwitch
          v-model:value="curEditItem.isShowEdit"
          title="编辑状态显示"
        />
        <BwConfigSelect
          v-model:value="curEditItem.option"
          title="操作"
          :options="[
            {
              label: '回调',
              value: BwFilterTableOptionEnum.callback,
            },
            {
              label: '页面跳转',
              value: BwFilterTableOptionEnum.link,
            },
          ]"
          :defaultValue="BwFilterTableOptionEnum.callback"
        />
        <div
          class="sub"
          v-if="curEditItem.option === BwFilterTableOptionEnum.link"
        >
          <BwConfigAppSelect
            title="跳转应用"
            v-model:value="curEditItem.linkApp"
            @change="methods.onChangeLinkApp"
          />
          <BwConfigSelect
            title="访问页面类型"
            v-model:value="curEditItem.pageType"
            :options="[
              {
                label: '普通表单',
                value: BwTableLinkPageTypeEnum.normalForm,
              },
              {
                label: '流程表单',
                value: BwTableLinkPageTypeEnum.flowForm,
              },
              {
                label: '自定义页面',
                value: BwTableLinkPageTypeEnum.customPage,
              },
              {
                label: '报表',
                value: BwTableLinkPageTypeEnum.report,
              },
              {
                label: '门户',
                value: BwTableLinkPageTypeEnum.portal,
              },
              {
                label: '其他',
                value: BwTableLinkPageTypeEnum.other,
              },
            ]"
            @change="methods.onChangePageType"
          />
          <BwConfigPageSelect
            v-model:value="curEditItem.linkedPage"
            :page-type="curEditItem.pageType"
            :link-app="curEditItem.linkApp"
            @change="methods.onChangeLinkPage"
            title="关联页面选择"
          />
          <BwConfigInput
            v-model:linkUrl="curEditItem.linkUrl"
            title="访问页面链接"
          />
          <BwConfigParams
            v-model:value="curEditItem.params"
            :options="dataKeyOptions"
          />
          <BwConfigSelect
            v-model:value="curEditItem.linkMode"
            :options="[
              {
                label: '当前页面跳转',
                value: 'location',
              },
              {
                label: '新开页面跳转',
                value: 'open',
              },
              {
                label: '新开页面窗口',
                value: 'openModal',
              },
            ]"
            title="跳转链接方式"
          />
        </div>
        <div class="sub" v-else>
          <BwConfigFunction v-model:value="curEditItem.callback" />
        </div>
        <BwConfigSwitch
          v-model:value="curEditItem.isCustomRender"
          title="是否自定义渲染"
        />
        <div class="sub" v-if="curEditItem.isCustomRender">
          <BwConfigFunction v-model:value="curEditItem.customRender" />
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  ref,
  unref,
  watch,
} from 'vue'
import { Button, Modal } from 'ant-design-vue'

import { BwFilterTableActionColumnModel } from './model'

import BwConfigInput from '../comItems/input/index.vue'
import BwConfigSelect from '../comItems/select/index.vue'
import BwConfigSwitch from '../comItems/switch/index.vue'
import BwConfigPageSelect from '../comItems/pageSelect/index.vue'
import BwConfigParams from '../comItems/params/index.vue'
import BwConfigAppSelect from '../comItems/appSelect/index.vue'
import BwConfigFunction from '../comItems/function/index.vue'

import { cloneDeep } from 'lodash-es'

import Sortable from 'sortablejs'
import { bwUtils } from '@/utils/main'
import { useAxiosResponse } from '@/api'
import { api } from '@/api/factory/sysFactory'
import {
  BwPageResultOutputSysDataObjectAppGetFieldOutput,
  SysApplicationAppGetInfoOuput,
} from '@bitwit/tenantapi'

import { BwTableLinkPageTypeEnum } from '../tableColumnConfig/enum'
import { BwFilterTableTreeListFieldsModel } from '../comItems/model'
import {
  BwFilterTableOptionEnum,
  BwFilterTableParamsValueTypeEnum,
} from '../comItems/enum'

export default defineComponent({
  name: 'BwFilterTableActionColumn',
  components: {
    Button,
    Modal,

    BwConfigInput,
    BwConfigSelect,
    BwConfigSwitch,
    BwConfigPageSelect,
    BwConfigParams,
    BwConfigAppSelect,
    BwConfigFunction,
  },
  props: {
    dataObjId: {
      type: [String, Number],
    },
    value: {
      type: [Array] as PropType<BwFilterTableActionColumnModel[]>,
    },
  },
  emits: ['update:value', 'change'],
  setup(props, { emit }) {
    /** 对象值 */
    const curActionColumn = computed({
      get: (): BwFilterTableActionColumnModel[] => {
        return props.value ?? []
      },
      set: (value) => {
        emit('update:value', value)
        emit('change', value)
      },
    })

    const sortList = ref()

    /** 当前编辑项 */
    const curEditItem = ref({} as BwFilterTableActionColumnModel)
    /** 当前编辑项下标 */
    const curEditIndex = ref(0)

    /** 是否编辑 */
    const isEdit = ref(false)

    const methods = {
      onChangeEditItem(item: BwFilterTableActionColumnModel, index: number) {
        curEditItem.value = cloneDeep(item)
        curEditIndex.value = index
        isEdit.value = true
      },
      onDeleteItem(index: number) {
        curActionColumn.value =
          curActionColumn.value.filter((_, i) => i !== index) ?? []
      },
      onAddItem() {
        curEditIndex.value = curActionColumn.value.length
        curEditItem.value = {
          id: bwUtils.getGuid(),
        }
        isEdit.value = true
      },
      onConfirm() {
        isEdit.value = false
        let arr = cloneDeep(curActionColumn.value)
        arr[curEditIndex.value] = unref(curEditItem)
        curActionColumn.value = arr
      },
      onChangeLinkApp() {
        curEditItem.value.pageType = undefined
        curEditItem.value.linkedPage = undefined
        curEditItem.value.linkUrl = undefined
        curEditItem.value.params = undefined
      },
      onChangePageType(pageType: string) {
        const curPageType = pageType
        /** 跳转页面url */
        let url = ''
        let appCode = ':appCode'
        let pageCode = ':pageCode'
        switch (curPageType) {
          case BwTableLinkPageTypeEnum.normalForm:
            url = `/detail/${appCode}/normalForm/${pageCode}`
            break

          case BwTableLinkPageTypeEnum.flowForm:
            url = `/detail/${appCode}/flowForm/${pageCode}`
            break

          case BwTableLinkPageTypeEnum.customPage:
            url = `/${appCode}/${pageCode}`
            break

          case BwTableLinkPageTypeEnum.report:
            url = `/${appCode}/${pageCode}`
            break

          case BwTableLinkPageTypeEnum.portal:
            url = `/${appCode}/${pageCode}`
            break

          case BwTableLinkPageTypeEnum.other:
            url = ``
            break

          default:
            url = ''
        }
        curEditItem.value.linkedPage = undefined
        curEditItem.value.linkUrl = url
      },
      onChangeLinkPage(linkPage: string) {
        let _pageType = curEditItem.value.pageType
        /** 当跳转页面详情页时添加dataId参数 */
        if (_pageType !== BwTableLinkPageTypeEnum.other) {
          let appCode = ''
          const linkAppId = curEditItem.value.linkApp
          api
            // .apiSysSettingInfoGet('0', linkAppId)
            .apiSysApplicationInfoGet(linkAppId)
            .then((res) => {
              const resData =
                useAxiosResponse<SysApplicationAppGetInfoOuput>(res)
              appCode =
                resData?.code ?? resData?.id?.toString() ?? linkAppId ?? ''
            })
            .catch((err) => {
              console.error(err)
            })
            .finally(() => {
              const routeParams = [
                {
                  key: 'appCode',
                  value: appCode ?? linkAppId,
                  valueType: BwFilterTableParamsValueTypeEnum.custom,
                },
                {
                  key: 'pageCode',
                  value: linkPage,
                  valueType: BwFilterTableParamsValueTypeEnum.custom,
                },
              ]
              curEditItem.value.params = routeParams
            })
        }
      },
      /** 初始化拖拽 */
      initSortableItem() {
        if (!sortList.value) return
        new Sortable(sortList.value, {
          animation: 150,
          onEnd: (evt) => {
            const { newIndex, oldIndex } = evt
            if (newIndex === oldIndex) return
            const arr = [...curActionColumn.value]
            const item = arr.splice(oldIndex ?? 0, 1)[0]
            arr.splice(newIndex ?? 0, 0, item)
            nextTick(() => {
              curActionColumn.value = [...arr]
            })
            return false
          },
        })
      },

      /** 获取数据字段类型 */
      getDataKeyOptions(dataObjectId?: string | number) {
        return new Promise((resolve, reject) => {
          api
            .apiSysDataObjectGetFieldsPost({
              dataObjectId: dataObjectId?.toString(),
            })
            .then((res) => {
              const resData =
                useAxiosResponse<BwPageResultOutputSysDataObjectAppGetFieldOutput>(
                  res
                )
              dataKeyOptions.value =
                resData?.rows
                  ?.filter((item) => item.id)
                  ?.map((item) => {
                    return {
                      label: item.code ?? '未命名字段',
                      value: item.id ?? '',
                    }
                  }) ?? []
              resolve(resData)
            })
            .catch((err) => {
              reject(err)
            })
        })
      },
    }

    /** 数据字段列表 */
    const dataKeyOptions = ref<BwFilterTableTreeListFieldsModel[]>([])
    watch(
      () => props.dataObjId,
      (newVal) => {
        methods.getDataKeyOptions(newVal)
      },
      { immediate: true }
    )

    onMounted(() => {
      methods.initSortableItem()
    })

    return {
      curActionColumn,
      sortList,
      isEdit,
      curEditItem,
      methods,
      dataKeyOptions,

      BwFilterTableOptionEnum,
      BwTableLinkPageTypeEnum,
    }
  },
})
</script>

<style lang="less" scoped>
.attr-item {
  max-height: 70%;
  overflow: auto;

  .attr-item-ul {
    padding: 8px;
    background: #edeff3;
    margin: 8px;

    .attr-item-ul-li {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      line-height: 28px;
      height: 28px;
      white-space: nowrap;

      .li-title {
        flex: 1;
        font-size: 12px;
      }

      .li-icon {
        font-size: 16px;
        cursor: pointer;
        margin-left: 8px;
        opacity: 0.6;

        &:hover {
          opacity: 1;
        }
      }
    }
  }

  .attr-item-add {
    width: 100%;
  }
}

.item-edit {
  padding: 24px;
  max-height: 580px;
  overflow: auto;

  .sub {
    background: #edeff3;
    border-radius: 3px;
    padding: 8px;
  }
}
</style>
